from django.contrib import admin
from .models import Question, Choice
from django.utils import timezone
import datetime

class ChoiceInline(admin.TabularInline):  # 更紧凑的表格布局
    model = Choice
    extra = 3
    fields = ['choice_text', 'votes']  # 明确指定内联编辑字段
    classes = ['collapse']  # 可折叠

@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    # 列表页配置
    list_display = ("question_text", "pub_date", "was_published_recently")
    list_filter = ["pub_date"]
    search_fields = ["question_text"]
    date_hierarchy = "pub_date"  # 添加日期导航
    
    # 编辑页配置
    fieldsets = [
        (None, {"fields": ["question_text"]}),
        ("Date Information", {
            "fields": ["pub_date"],
            "classes": ["collapse"]
        }),
    ]
    inlines = [ChoiceInline]

    # 使用模型方法但添加admin显示控制
    @admin.display(
        boolean=True,
        ordering="pub_date",
        description="Published recently?",
    )
    def was_published_recently(self, obj):
        return obj.was_published_recently()  # 调用模型中的方法

@admin.register(Choice)
class ChoiceAdmin(admin.ModelAdmin):
    list_display = ("question", "choice_text", "votes")
    list_select_related = ['question']  # 优化查询性能
    search_fields = ["choice_text", "question__question_text"]  # 支持跨关联搜索
    list_filter = ["question"]  # 按问题筛选